<script setup lang="ts">
import PageContainer from '@/components/PageContainer.vue';
import ArticleEdit from '@/views/article/components/ArticleEdit.vue';
import ChannelSelect from '@/views/article/components/ChannelSelect.vue';
import { ref,computed,onMounted } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { Edit,Delete } from '@element-plus/icons-vue';
import { artGetChannelsService,artDelService,artGetListService } from '../../api/article';
import { useRouter } from 'vue-router'; // 导入路由
import { D, N } from 'msw/lib/core/HttpResponse-BbwAqLE_';

interface ChannelItem {
  id: number;
  name: string;
  alias: string;
}

interface ArticleItem {
  id: number;
  title: string;
  cate_name: string;
  state: string;
  pub_date: string;
  cover: string,
  content: string,
  word_count: number,
  chapter_count: number,
  last_update: Date
}

interface ChannelResponse<T = any> {
  data: {
    code: string;
    msg: string;
    data: T;
  }
}

interface ArticleResponse<T = any> {
  data: {
    code: string;
    msg: string;
    data: T;
  }
}

const router = useRouter(); // 获取路由实例
const articleList=ref<ArticleItem[]>([]);
const receivedList=ref<ChannelItem[]>([]);
const selectedcategory=ref<string>('');
const selectedState=ref<string>('');
const searchCategory=ref<string>('')
const searchState=ref<string>('')
const currentPage=ref(1);
const pageSize=ref(9);
const total=ref(articleList.value.length);
const articleEditref=ref<InstanceType<typeof ArticleEdit> | null>(null);
const loading=ref(false);

const getArtcleList = async ():Promise<void> => {
  loading.value = true;
  try {
    const res = await artGetListService();
    articleList.value = res.data.data;
    // 手动重置页码，触发 filterArticleList 重新计算
    currentPage.value = 1; 
  } catch (error) {
    ElMessage({ message: '获取文章列表失败', type: 'error' });
  } finally {
    loading.value = false;
  }
};
getArtcleList();

const handleSizeChange=(newSize):void=>{
    pageSize.value=newSize;
    currentPage.value=1;
};
const handlePageChange=(newPage):void=>{
    currentPage.value=newPage;
};
const filterArticleList = computed<ArticleItem[]>(() => {
  let filtered = articleList.value.filter(item => 
    (searchCategory.value ? item.cate_name === searchCategory.value : true) &&
    (searchState.value ? item.state === searchState.value : true)
  );
  total.value = filtered.length;
  const maxPage = Math.ceil(total.value / pageSize.value);
  if (currentPage.value > maxPage) currentPage.value = maxPage;
  const start = (currentPage.value - 1) * pageSize.value;
  
  // 格式化发布时间：去掉 T 和 Z，保留年月日
  return filtered.slice(start, start + pageSize.value).map(item => ({
    ...item,
    pub_date: item.pub_date ? item.pub_date.split('T')[0] : '' 
    // 示例：2023-10-01T00:00:00.000Z → 2023-10-01
  }));
});
const handleSearch=():void=>{
    loading.value=true;
    setTimeout(()=>{
        loading.value=false;
        searchCategory.value=selectedcategory.value;
        searchState.value=selectedState.value;
        currentPage.value=1;
    },500);
};
const handleReset=():void=>{
    selectedcategory.value='';
    selectedState.value='';
    searchCategory.value='';
    searchState.value='';
    currentPage.value=1;
};
const onAddArticle=():void=>{
    articleEditref.value.open();
};
const onEditArticle=(row):void=>{
    articleEditref.value.open(row);
};
const onDelArticle=(row):void=>{
    ElMessageBox.confirm(`确定删除文章《${row.title}》吗？`,'提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
    }).then(()=>{handleDeleteArticle(row.id)
    }).catch(()=>{});
};

const handleDeleteArticle = async (id):Promise<void> => { // 改为 async 函数，支持 await 调用
  try {
    // 1. 调用后端删除接口（传入文章ID）
    const res = await artDelService(id) as ArticleResponse; 
    
    // 2. 判断接口是否调用成功（后端返回 code: 0000 才是真成功）
    if (res.data.code === '0000') {
      // 3. 接口成功后，更新前端列表（过滤掉已删除的文章）
      const currentPageBeforeDelete = currentPage.value;
      articleList.value = articleList.value.filter(item => item.id !== id);
      total.value = articleList.value.length;
      
      // 4. 处理分页：若当前页无数据，自动跳转到上一页
      const itemsOnCurrentPage = filterArticleList.value.length;
      if (itemsOnCurrentPage === 0 && currentPageBeforeDelete > 1) {
        currentPage.value = currentPageBeforeDelete - 1;
      }
      
      // 5. 提示用户删除成功
      ElMessage({ message: '文章删除成功', type: 'success' });
    } else {
      // 6. 接口返回业务错误（如无权限），提示用户
      ElMessage({ message: res.data.msg, type: 'error' });
    }
  } catch (err) {
    // 7. 捕获网络错误（如断网、超时）
    ElMessage({ message: '删除失败：网络异常', type: 'error' });
    console.error('删除接口调用失败：', err); // 方便调试
  }
};
const handleAddArticle=(newArticle):void=>{
    articleList.value.unshift(newArticle);
    total.value=articleList.value.length;
};
const handleEditArticle=(updatedArticle):void=>{
    const index=articleList.value.findIndex(item=>item.id===updatedArticle.id);
    if(index!==-1){
        articleList.value.splice(index,1,updatedArticle);
    }
};
const getChannelList = async ():Promise<void> => {
  try {
    const res = await artGetChannelsService() as ChannelResponse<ChannelItem[]>;
    // 只在后端返回成功码时更新列表
    if (res.data.code === '0000') {
      receivedList.value = res.data.data || []; // 避免null
      ElMessage.success('获取分类列表成功');
    } else {
      // 后端返回业务错误（如Token失效、数据库错误）
      ElMessage.error(`获取失败：${res.data.msg}`);
      receivedList.value = []; // 空数组避免表格异常
    }
  } catch (err) {
    // 前端网络错误（超时、断网）
    ElMessage.error('获取分类列表失败：网络异常');
    receivedList.value = [];
  }
};
onMounted(()=>{
    getChannelList();
});
// 点击小说标题跳转到详情页
const goToNovelDetail = (novel):void => {
  router.push(`/article/detail/${novel.id}`);
};

</script>

<template>
    <page-container title="作品管理">
        <template #extra>
            <div style="display: flex; align-items: center; margin-left: auto;">
                <el-button type="primary" @click="onAddArticle">创建作品</el-button>
            </div>
        </template>
        <el-form inline>
            <el-form-item label="小说标题">
                <ChannelSelect :options="receivedList" v-model="selectedcategory"></ChannelSelect>
            </el-form-item>
            <el-form-item>
                <el-select v-model="selectedState" style="width: 180px">
                    <el-option label="连载" value="连载"></el-option>
                    <el-option label="完结" value="完结"></el-option>
                    <el-option label="停更" value="停更"></el-option>
                    <el-option label="下架" value="下架"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="filterArticleList" style="width: 100%;">
            <el-table-column prop="title" label="小说标题">
                <template #default="{row}">
                    <el-link type="primary" @click="goToNovelDetail(row)">
                        {{ row.title }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column prop="cate_name" label="小说分类"></el-table-column>
            <el-table-column prop="state" label="发布状态"></el-table-column>
            <el-table-column prop="pub_date" label="发布时间"></el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="{row}">
                    <el-button type="primary" @click="onEditArticle(row)" :icon="Edit" circle plain></el-button>
                    <el-button type="danger" @click="onDelArticle(row)" :icon="Delete" circle plain></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <div class="empty-box">
                    <el-empty description="No data"></el-empty>
                </div>
            </template>
        </el-table>
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            style="margin-top: 20px; text-align: right"
            background
            layout="prev, pager, next,total, sizes,jumper"
            :page-sizes="[5,6,8,9]"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
        <ArticleEdit ref="articleEditref" :options="receivedList" @add-article="handleAddArticle" @edit-article="handleEditArticle"/>
    </page-container>
</template>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 搜索区域样式 */
.el-form {
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.el-form-item {
  margin-right: 16px !important;
  margin-bottom: 12px !important;
}

/* 表格样式增强 */
.el-table {
  padding: 10px 0;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: none !important;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 500 !important;
  color: #4e5969 !important;
  border-bottom: 1px solid #f0f2f5 !important;
}

.el-table tr:hover > td {
  background-color: #f5f8ff !important;
}

.el-table__empty-block {
  min-height: 300px !important;
}

/* 表格列内容样式 */
.el-link {
  transition: all 0.2s;
}

.el-link:hover {
  color: #4096ff !important;
  text-decoration: underline;
}

/* 操作按钮样式优化 */
:deep(.el-button) {
  transition: all 0.2s;
}

:deep(.el-button--primary.is-plain) {
  color: #4096ff;
  border-color: #4096ff;
}

:deep(.el-button--primary.is-plain:hover) {
  background-color: #4096ff;
  color: #fff;
}

:deep(.el-button--danger.is-plain) {
  color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger.is-plain:hover) {
  background-color: #f56c6c;
  color: #fff;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 空状态样式 */
.empty-box {
  padding: 40px 0;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .el-form {
    padding: 12px;
  }
  
  .el-form-item {
    width: 100% !important;
    margin-right: 0 !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-table-column {
    padding: 0 5px !important;
  }
  
  .el-pagination {
    padding: 12px;
    font-size: 12px;
  }
}

/* 标题列样式 */
:deep(.el-table-column--selection) {
  width: 50px !important;
}

/* 操作列按钮间距 */
:deep(.el-table-column__content .el-button) {
  margin-right: 6px;
}

:deep(.el-table-column__content .el-button:last-child) {
  margin-right: 0;
}

</style>